#include <iostream>
#include <cstring>
#include <unistd.h>
#include <netinet/in.h> // 包含sockaddr_in结构体和相关常量
#include <arpa/inet.h>  // 包含IP地址转换函数
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage: ./client ip port" << std::endl;
        exit(1);
    }

    int sockfd=socket(AF_INET,0,SOCK_STREAM);

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    struct sockaddr_in server_des;
    memset(&server_des, 0, sizeof(server_des)); // 清零结构体
    struct in_addr addr;
    inet_pton(AF_INET, ip.c_str(), &addr);
    server_des.sin_family = AF_INET;
    server_des.sin_port = htons(port);
    server_des.sin_addr = addr;

    //连接服务端：
    int n=connect(sockfd,(struct sockaddr*)&server_des,sizeof(server_des));
    if(n<0)
    {
        std::cout<<"connect fail!"<<std::endl;
        exit(2);
    }
    while(1)
    {
        std::cout<<"Please Enter:"<<std::endl;
        std::string line;
        getline(std::cin,line);
        write(sockfd,line.c_str(),line.size());

        //接受服务端发回来的消息：
        char buffer[1024];
        int n=read(sockfd,buffer,sizeof(buffer)-1);
        if(n<0)
        {
            std::cout<<"read fail!"<<std::endl;
            exit(3);
        }
        buffer[n]='0';
        std::cout<<buffer<<std::endl;
    }
    close(sockfd);
    return 0;
}